package hisp;

import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import javax.crypto.Cipher;

public class PublicKeyEncryption {
	private KeyPair keyPair;
	String xform = "RSA/NONE/PKCS1PADDING";
	
	public PublicKeyEncryption() {
	    // Generate a key-pair
	    KeyPairGenerator kpg;
		try {
			kpg = KeyPairGenerator.getInstance("RSA");
		    kpg.initialize(512); // 512 is the keysize.
		    keyPair = kpg.generateKeyPair();  
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
  
	}
	
	public byte[] encrypt(byte[] inpBytes) throws Exception {
		Cipher cipher = Cipher.getInstance(xform);
		cipher.init(Cipher.ENCRYPT_MODE, keyPair.getPublic());
		return cipher.doFinal(inpBytes);
	}
	
	public byte[] decrypt(byte[] inpBytes) throws Exception{
		Cipher cipher = Cipher.getInstance(xform);
		cipher.init(Cipher.DECRYPT_MODE, keyPair.getPrivate());
		return cipher.doFinal(inpBytes);
	}
}